import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, ProfileOutlined, ReloadOutlined, MinusSquareOutlined,
  PlusSquareOutlined, EditOutlined, ExperimentOutlined, CopyOutlined, SwapOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, Checkbox, DatePicker, Tabs } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/shipSRM/chlogo.png'

import {
  openNotification_util, fetchsync_util, useexcelauto,
  getCurrentDate_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS,
  addkey_for_mxdata
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
const { Option } = Select;
import Sortable from '../newmes/sortable.js';
import { use_gysbg_initcolmun } from '../gyszx/use_gyszx_config.js';
import useStore from '../../useStore.js'
import { clearCache, useDidCache, useDidRecover, dropByCacheKey } from 'react-router-cache-route';
import ResizableTable from '../newmes/Resize_table_hook.js';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const Gysbg_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_gysbg_initcolmun)
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();


  useEffect(() => {
    querylist()
    storage[`Pc_gysbg_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gysbg_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_gysbg_list__initsize_${storage.userid}`] ? setinitSize(storage[`Pc_gysbg_list__initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }

  const querylist = async () => {
    setisloading(true)
    storage[`Pc_gysbg_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gysbg_list_${storage.userid}`])) : setcolumnarr(columnarr)
    let rtdata = await fetchsync_util("/admin/gyszx/gysbglb", 'POST', {}, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)

    });

    if (storage.yhlx == "租户用户") {
      rtdata.resultdata = rtdata.resultdata.filter(item => item.gysdm == storage.ygbh)
    }

    setlistdata(dealnullorundenfined(rtdata.resultdata))

    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    if (listdata.some(item => item.clzt == "未审批")) {
      openNotification_util("已有未审批的变更记录，请先处理！")
      return
    }
    storage.pre_gysbg_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('gysbg_form')
    setnowroute({ ...{ route: "/shipSRM/gyszx/gysbg_form", title: "供应商档案变更_新增" } })
  }
  /**
   * 编辑
   */
  const handleEdit = async (data, type) => {
    storage.pre_gysbg_item = JSON.stringify({ data, type })
    dropByCacheKey('gysbg_form')
    setnowroute({ ...{ route: "/shipSRM/gyszx/gysbg_form", title: "供应商档案变更_" + `${type == "edit" ? "编辑" : "查看"}` } })

  }
  /**
   * 删除
   */
  const handledelete = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据删除!")
    }
    else {
      let rtdata = await fetchsync_util("/admin/gyszx/delete_gysbg", 'POST', { selectedRows }, "json")
      rtdata.rtstatus ? querylist() : 1
    }
  }
  /**
   * 导出
   */
  const handleExport = async () => {
    let filtercol = JSON.parse(JSON.stringify(columnarr)).filter(item => item.show == true)
    filtercol.forEach(element => {
      element.width = element.width ? element.width / 7 : 10
    });
    useexcelauto(selectedRows, filtercol, '供应商档案')
  }


  const TabPaneItem = (title, listdata, columnarr, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{listdata.length}</span></span>}
      key={key}>
      {isloading ?
        (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
          <Spin /></div>)
        :
        (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
          width={collapsed ? "94%" : "84%"}
          storageName={`Pc_gysbg_list_${storage.userid}`}
          sfdoubleclick="false" ifhiddencchangeselecttype="true"
          selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
          showCz={{ showView: true }}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          handleDelete={(data, type) => handledelete(data, type)}
          defaultPageSize={10}
          bordered
          handleselectson={(selectedRows, selectedRowKeys) => {
            setselectedRows(selectedRows)
            setselectedRowKeys(selectedRowKeys)
          }}
        />)
      }
    </Tabs.TabPane>
  }

  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem",paddingRight:"1%"
    }}>



      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw",paddingRight:"1vw"
        }}>

          <div style={styleobj.linestyleflex}>
            <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#666666" }}>工具栏</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷新</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />发起变更</Button>


          </div>

          <div style={{ width: "100%", height: "0.3vw", backgroundColor: "#F1F1F1" }}></div>
          <IconFont type="setting" style={{ position: 'absolute', right: '2vw', top: '1.2rem', fontSize: "1.5rem" }}
            onClick={e => setIsModalOpen(true)} />
          {ifshow && <Sortable tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_gysbg_list_${storage.userid}`} open={isModalOpen} handleOpen={(data) => { setIsModalOpen(data); }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_gysbg_list__initsize_${storage.userid}`] = data; }}
          />}
          {storage.yhlx == "管理用户" && <Tabs defaultActiveKey="1" className='task-tabs' >
            {TabPaneItem("未审批", addkey_for_mxdata(listdata.filter(item => item.clzt == "未审批")), columnarr, "1")}
            {TabPaneItem("已通过", addkey_for_mxdata(listdata.filter(item => item.clzt == "已通过")), columnarr, "2")}
            {TabPaneItem("已驳回", addkey_for_mxdata(listdata.filter(item => item.clzt == "已驳回")), columnarr, "3")}
          </Tabs>
          }
          {storage.yhlx == "租户用户" && <ResizableTable tabledata={listdata} tablecolnum={columnarr}
            width={collapsed ? "94%" : "84%"}
            storageName={`Pc_gysbg_list_${storage.userid}`}
            sfdoubleclick="false" ifhiddencchangeselecttype="true"
            selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
            showCz={{ showView: true }}
            handleEdit={(data) => handleEdit(data, "edit")}
            handleView={(data) => handleEdit(data, "view")}
            handleDelete={(data, type) => handledelete(data, type)}
            defaultPageSize={10}
            bordered
            handleselectson={(selectedRows, selectedRowKeys) => {
              setselectedRows(selectedRows)
              setselectedRowKeys(selectedRowKeys)
            }}
          />
          }
        </div>

      </div>
    </div>
  )
}


export default Gysbg_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}